ajax后退操作解决办法

作者:matrix 被围观: 5,405 次 发布时间:2017-09-19 分类:零零星星 | 无评论 »

这是一个创建于 2415 天前的主题,其中的信息可能已经有所发展或是发生改变。

使用github项目

https://github.com/browserstate/history.js

问题场景

移动端网页列表(上拉加载执行ajax请求)中要在点击item详情页跳转后可返回,且返回页面中需要看到或定位到点击的来源位置。

测试

要实现准确定位,刚开始想的基本原理也就是俩页面之间跳转传递分页数和滚动条位置的数量,想过sessionstorage对象来存储或是用url中hash值、query参数来传递相关状态,列表页面中进行判断请求数据且修改ajax加载的分页起始数,但是url中的参数需要和后台进行协调才可以达到满意的效果,实现起来也麻烦。搜索找到好多方案 貌似history.js兼容各大浏览器,效果应该比较理想。

JQ后加载History的js文件:/history.js/scripts/bundled/html4+html5/jquery.history.js

测试分页使用scrollPagination的JQ插件实现翻页:

var urlscroll   = '';
var p = 1;

//获取缓存数据
//dom数据以及分页起始数
var dom = !!History.getState().data.dom?History.getState().data.dom:'';
var page = !!History.getState().data.p?History.getState().data.p:p;
p = page;
$(".test_list").append(dom);//追加缓存的dom
//end

$('.test_list').scrollPagination({
    'contentPage': urlscroll, // the url you are fetching the results
    'contentData': {'page':p}, // these are the variables you can pass to the request, for example: children().size() to know which page you are
    'scrollTarget': $(window), // who gonna scroll? in this example, the full window
    'heightOffset': 0, // it gonna request when scroll is 10 pixels before the page ends
    'bottomHeight': $('.footer').height(), // it gonna request when scroll is 10 pixels before the page ends
    'beforeLoad': function(){ // before load function, you can display a preloader div
        //$('#loading-pic').show();
        this.flagRequesting = 0;
    },
    'afterLoad': function(elementsLoaded){ // after loading content, you can use this function to animate your new elements

    //记录分页的dom数据
        for (var i = 0; i < elementsLoaded.length; i++) {
            dom += $(elementsLoaded[i]).html();
        }
        if(!!dom) History.pushState({'dom':dom,'p':this.contentData.page+1});//记录最后一次分页加载的dom数据以及下一页的起始数
        //end

        this.contentData.page++; 
         $(".test_list").append('<img src="/mobile/img/ads.jpg" class="ads_img">');

        }
    this.flagRequesting = 1;
    }
});

上面代码仅测试,需自行修改。
主要起作用的位置是 记录分页的dom数据获取缓存数据 两处注释块。
道理还是那样,只是更优化了些。这里缓存了所有ajax分页的DOM数据和请求的最后的页码,当返回到列表页面的时候获取缓存DOM并加载,起始的分页数也会还原。
history.js内部也是使用sessionstorage来缓存相关数据,所以设置state数据的时候需要将DOM对象转换为String字符串数据就可以缓存整个分页数据。
实际使用中会发现个别时候item详情页面中执行history.go(-1)或者点击A标签链接返回到列表页面的时候缓存的分页DOM数据可以正常的显示,但是滚动条定位就没达到想要的效果,所以要完美应该在获取缓存数据的时候添加一个scrollTop滚动条的复位操作,这样应该就巴适了。

嗯~~今天遇到的这个问题还好解决了,感谢开源奉献的人们。

peace~

参考:
http://www.cnblogs.com/songbyjson/p/4886615.html

五种解决方案:http://www.cnblogs.com/snandy/archive/2011/09/18/2180102.html

其他文章:
本文固定链接:https://www.hhtjim.com/ajax-back-operation-solution.html
matrix
本文章由 matrix 于2017年09月19日发布在零零星星分类下,目前没有通告,你可以至底部留下评论。
转载请注明:ajax后退操作解决办法-HHTjim'S 部落格
关键字:

添加新评论 »

 🙈 😱 😂 😛 😭 😳 😀 😆 👿 😉 😯 😮 😕 😎 😐 😥 😡 😈 💡

插入图片

NOTICE: You should type some Chinese word (like “你好”) in your comment to pass the spam-check, thanks for your patience!